#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#define PORT		9000
#define IPADDRESS	"127.0.0.100"

char *
sock_addr(int s, char *buf, size_t bufsize)
{
	int z;		//status return code
	struct sockaddr_in adr_inet;	//socket address
	socklen_t len_inet;	// size of socket address length

	len_inet = sizeof(adr_inet);

	z = getsockname(s, (struct sockaddr *) &adr_inet, &len_inet);
	if(z == -1) {
		perror("getsockname()");
		exit(1);
	}

	snprintf(buf, bufsize, "%s:%u", inet_ntoa(adr_inet.sin_addr), (unsigned) ntohs(adr_inet.sin_port));

	return buf;
}

int main(int argc, char **argv)
{
	int z;		//status return code
	int sck_inet;	//socket fd
	struct sockaddr_in adr_inet;	//socket address
	int len_inet;	//socket address length
	char buf[64];

	sck_inet = socket(AF_INET, SOCK_STREAM, 0);
	if(sck_inet == -1) {
		perror("socket()");
		exit(1);
	}

	// clear socket address
	memset(&adr_inet, 0, sizeof(adr_inet));

	// initialize socket address
	adr_inet.sin_family = AF_INET;
	adr_inet.sin_port = htons(PORT);
	inet_aton(IPADDRESS, &adr_inet.sin_addr);

	// get socket address length
	len_inet = sizeof(adr_inet);

	// bind socket with fd
	z = bind(sck_inet, (struct sockaddr *) &adr_inet, len_inet);
	if(z == -1) {
		perror("bind()");
		exit(1);
	}

	// test socket addres function
	if(! sock_addr(sck_inet, buf, sizeof(buf))) {
		perror("sock_addr()");
		exit(1);
	}
	printf("Address is %s\n", buf);

	return 0;	
}
